public class Solution {
    public int surfaceArea(int[][] grid) {
        int ans = 0;
        int xlen = grid.length;
        int ylen = grid[0].length;
        for (int i = 0; i < xlen; i++) {
            for (int j = 0; j < ylen; j++) {
                int v = grid[i][j];
                int pre=0, next=0, left=0, right = 0;
                if (i-1 >= 0) {
                    pre = grid[i-1][j];
                }
                if (i+1 < xlen) {
                    next = grid[i+1][j];
                }
                if (j-1 >= 0) {
                    left = grid[i][j-1];
                }
                if (j+1 < ylen) {
                    right = grid[i][j+1];
                }
                int a = 0;
                if (v > 0) {a = 2;}
                ans += a + Math.max(v-pre, 0) + Math.max(v-next, 0) + Math.max(v-left, 0) + Math.max(v-right,0);
            }    // a这里易错，max方法的运用
        }
        return ans;
    }

}

// 注意这个方法的运用运用数组去循环取元素

class Solution2 {
    public int surfaceArea(int[][] grid) {
        int[] dr = new int[]{0, 1, 0, -1};
        int[] dc = new int[]{1, 0, -1, 0};

        int N = grid.length;
        int ans = 0;

        for (int r = 0; r < N; ++r) {
            for (int c = 0; c < N; ++c) {
                if (grid[r][c] > 0) {
                    ans += 2;
                    for (int k = 0; k < 4; ++k) {
                        int nr = r + dr[k];
                        int nc = c + dc[k];
                        int nv = 0;
                        if (0 <= nr && nr < N && 0 <= nc && nc < N) {
                            nv = grid[nr][nc];
                        }

                        ans += Math.max(grid[r][c] - nv, 0);
                    }
                }
            }
        }

        return ans;
    }
}

//作者：LeetCode-Solution
//        链接：https://leetcode-cn.com/problems/surface-area-of-3d-shapes/solution/san-wei-xing-ti-de-biao-mian-ji-by-leetcode-soluti/
//        来源：力扣（LeetCode）
//        著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
